package pl.auction_search.model;

import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import pl.auction_search.search.Result;

/**
 * SearchModel for the application.
 **/
public class SearchResultModel implements ISearchResultModel<Result> {
	public static class SearchCategory implements ISearchCategory<Result> {
		protected String name;
		protected List<Result> items_;
		
		public SearchCategory(String name, List<Result> items) {
			this.name = name;
			items_ = items;
		}
		@Override public String getName() {
			return name;
		}
		@Override public List<Result> list() {
			return items_;
		}
		@Override public ISearchCategory<Result> add(Result r) {
			items_.add(r);
			return this;
		}
		@Override public Result[] toArray() {
			return (items_ == null) ?
				new Result[]{}:
				items_.toArray(new Result[items_.size()]);
		}
		@Override public String toString() {
			return getName();
		}
	}//
	
	protected Map<String, ISearchCategory<Result>> categories_ = new HashMap<String, ISearchCategory<Result>>();

	@Override public ISearchCategory<Result> getCategory(String name) {
		return categories_.get(name);
	}

	@Override public Collection<ISearchCategory<Result>> listCategories() {
		if(categories_ == null) return Collections.emptyList(); 
		return Collections.unmodifiableCollection(categories_.values()); 
	}

	@Override public void add(Result r) {
		ISearchCategory<Result> category = this.getCategory(r.getCategory());
		if(category == null){
			category = new SearchCategory(r.getCategory(), new LinkedList<Result>());
			add(category);
		}
		category.add(r);
	}
	protected void add(ISearchCategory<Result> c) {
		categories_.put(c.getName(), c);
	}

	protected List<Runnable> changeListeners = new LinkedList<Runnable>();
	@Override public void registerChangeListener(Runnable r) {
		changeListeners.add(r);
	}

}
